package com.fanilycar51.mvp.common;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.OkHttpClient;

/**
 * 应用启动初始化类
 */
public class AppAplication extends Application {
    //定义全局的Context对象
    public static Context context;
    //定义全局的Handler对象
    public static Handler handler;
    //定义主线程对象
    public static Thread mainThread;
    //定义主线程的线程ID
    public static int mainThreadId;

    //设备信息
    //系统信息
    public static String SY_SY = "android";
    //设备ID
    public static String sy_di;
    //客户端版本
    public static String sy_cv;



    //返回AppLicatinon单例的方法
    private static volatile AppAplication application;

    public static AppAplication getInstance() {
        if (application == null) {
            synchronized (AppAplication.class) {
                if (application == null) {
                    application = new AppAplication();
                }
            }
        }
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        //解决65536的报错,分包处理
        MultiDex.install(this);

        //初始化上下文等对象
        initConnmon();
        //获取设备信息
        initSystemMsg();

        //初始化okHttpUtils
        initOKhttp();

        //初始化异常处理类,上线后打开这个方法
//        initCrashHandler();

        //配置本地数据库的操作
//        setupDatabase();

    }



    /**
     * 设置本地数据库
     */
    private void setupDatabase() {
        //创建shop.db数据库
//        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "shop.db", null);
        //获取可写数据库
//        SQLiteDatabase db = helper.getWritableDatabase();
        //获取数据库对象
//        DaoMaster daoMaster = new DaoMaster(db);
        //获取Dao对象管理者
//        daoSession = daoMaster.newSession();

    }
//    public static DaoSession getDaoInstant() {
//        return daoSession;
//    }

    /**
     * 初始化OkHttpUtils
     */
    private void initOKhttp() {
        //配置支持Https请求
        //配置Https证书
        try {
            //支持指定证书认证的Https请求
//            HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(new InputStream[
//                    ]{getAssets().open("https.cer")}, null, null);
            //支持所有的Https请求
            HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
            CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(new LoggerInterceptor("TAG"))
                    .connectTimeout(5000L, TimeUnit.MILLISECONDS)
                    .readTimeout(5000L, TimeUnit.MILLISECONDS)
                    .cookieJar(cookieJar)
                    .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                    //其他配置
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    })
                    .build();
            OkHttpUtils.initClient(okHttpClient);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化异常处理
     */
    private void initCrashHandler() {
        CrashHandler.getInstance().init();
    }

    /**
     * 获取设备信息的方法
     */
    private void initSystemMsg() {
        //获取设备版版本号
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        sy_cv = String.valueOf(currentapiVersion);
        //获取设备ID
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        sy_di = tm.getDeviceId();
    }

    /**
     * 初始化一些常用的对象
     */
    private void initConnmon() {
        context = getApplicationContext();
        handler = new Handler();
        mainThread = Thread.currentThread();
        mainThreadId = android.os.Process.myTid();
    }


    /**
     * 判断当前进程是不是UI进程的方法
     *
     * @param context
     * @return
     */
    public static boolean inMainProcess(Context context) {
        String packageName = context.getPackageName();
        String processName = getProcessName(context);
        return packageName.equals(processName);
    }


    /**
     * 获取当前进程名
     *
     * @param context
     * @return 进程名
     */
    public static String getProcessName(Context context) {
        String processName = null;

        // ActivityManager
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));

        while (true) {
            for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) {
                if (info.pid == android.os.Process.myPid()) {
                    processName = info.processName;
                    break;
                }
            }

            // go home
            if (!TextUtils.isEmpty(processName)) {
                return processName;
            }

            // take a rest and again
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}
